﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using yc.Dal;

namespace yc.Site.Controllers
{
    public class OperatorController : Controller
    {
        public ActionResult Index()
        {
			var db = new DBContext();
			
			var pager = db.SysUser.ToPager();
			return View(pager);
        }

		public ActionResult Edit(int Id = 0)
		{
			var db = new DBContext();
			var item = new SysUser();
			if (Id != 0) item = db.SysUser.Find(Id);
			item.Password = "";
			return View(item);
		}

		[HttpPost, ActionName("Edit")]
		public ActionResult PostEdit(int Id = 0)
		{
			var db = new DBContext();
			db.Configuration.AutoDetectChangesEnabled = true;
			var item = new SysUser();
			var oldpwd="";
			if (Id != 0){
				item = db.SysUser.Find(Id);
				oldpwd=item.Password;
			}
			if (TryUpdateModel(item))
			{
				if (Id == 0)
				{
					if (string.IsNullOrWhiteSpace(item.Password))
					{
						ModelState.AddModelError("Password", "密码不能为空！");
						return View(item);
					}
					item.Password = MD5.Encrypt(item.Password);
					db.SysUser.Add(item);
				}
				else
				{
					if (string.IsNullOrWhiteSpace(item.Password)) item.Password = oldpwd;
					else item.Password = MD5.Encrypt(item.Password);
				}
				db.SaveChanges();
				ModelState.AddModelError("", "保存成功");
			}
			return View(item);
		}

		[HttpPost]
		public ActionResult Del(int id = 0)
		{
			if (id == 0) return Json(new { res = false, msg = "数据非法" });
			var db = new DBContext();
			db.Configuration.AutoDetectChangesEnabled = true;
			var item = db.SysUser.Find(id);
			if (item == null) return Json(new { res = false, msg = "数据非法" });
			db.SysUser.Remove(item);
			db.SaveChanges();
			Common.Dictionary.RemoveAll(p => p.ID.Equals(id));
			return Json(new { res = true, msg = "删除成功" });
		}
    }
}
